package com.luoxiang.socialandroid.activity;

import static com.luoxiang.lib_common.common.Constants.MmkvConst.EXTRA;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.TOKEN;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.USERID;

import static io.reactivex.internal.schedulers.SchedulerPoolFactory.start;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.luoxiang.socialandroid.R;
import com.luoxiang.socialandroid.adapter.Tezhi4RecyAdapter;
import com.luoxiang.socialandroid.base.BaseActivity;
import com.luoxiang.socialandroid.bean.LableBean;
import com.luoxiang.socialandroid.bean.NumberBean;
import com.luoxiang.socialandroid.utils.AESUtil;
import com.luoxiang.socialandroid.utils.CustomClickListener;
import com.luoxiang.socialandroid.utils.MmkvUtil;
import com.luoxiang.socialandroid.utils.NetUtils2;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class Tezhi4Activity extends BaseActivity {
    private String tokens;
    private TextView btn_goup;
    private RecyclerView rc_tezhi4;
    private Tezhi4RecyAdapter adapter;
    private ArrayList<String> selectIds = new ArrayList<>();
    private int datingModeId, emotioRelationId, targetAgeId;
    private String labelIds;
    private int mUserid;
    private ImageView icon_back;
    private TextView tv_manorgirltezhi;

    @Override
    protected void initListener() {

        btn_goup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (btn_goup.getText().toString().equals(getString(R.string.mi_xuanhaol))) {
                    mUserid = MmkvUtil.INSTANCE.decodeInt(USERID);
                    datingModeId = MmkvUtil.INSTANCE.decodeInt("datingModeId");
                    emotioRelationId = MmkvUtil.INSTANCE.decodeInt("emotioRelationId");
                    targetAgeId = MmkvUtil.INSTANCE.decodeInt("targetAgeId");
                    JSONObject jsonObject = new JSONObject();
                    RequestBody requestBody = null;
                    try {
                        labelIds = TextUtils.join(",", selectIds);
                        jsonObject.put("userId", mUserid);
                        jsonObject.put("datingModeId", Tezhi4Activity.this.datingModeId);
                        jsonObject.put("emotioRelationId", Tezhi4Activity.this.emotioRelationId);
                        jsonObject.put("targetAgeId", Tezhi4Activity.this.targetAgeId);
                        jsonObject.put("labelIds", labelIds);
                        requestBody = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), jsonObject.toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    addUserTrait(EXTRA, requestBody);
                    Intent intent = new Intent(Tezhi4Activity.this, HomeActivity.class);
                    startActivity(intent);
                    MmkvUtil.INSTANCE.encode("keybutezhi", "ok");
                    Tezhi1Activity.instance.finish();
                    Tezhi2Activity.instance.finish();
                    Tezhi3Activity.instance.finish();
                    finish();
                } else {
                    ToastUtils.showShort(R.string.zuishaoxuanzejigebiaoqian);
                }

            }
        });
        icon_back.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                finish();
            }

            @Override
            protected void onFastClick() {

            }
        });
    }


    private void addUserTrait(String extra, RequestBody body) {
        NetUtils2.getInstance().getApiService().addUserTrait(tokens, EXTRA, body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LogUtils.i("decryptStr999", decryptStr);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            start();
            return false;

        } else {

            return super.onKeyDown(keyCode, event);

        }
    }


    @Override
    protected void initLayout(Bundle savedInstanceState) {
        setContentView(R.layout.activity_tezhi4);
        setStatusBarTranslucent();

    }

    @Override
    protected void initView() {
        rc_tezhi4 = findViewById(R.id.rc_tezhi4);
        getRequest();
        tokens = MmkvUtil.INSTANCE.decodeString(TOKEN);
        rc_tezhi4 = findViewById(R.id.rc_tezhi4);
        btn_goup = findViewById(R.id.btn_goup);
        icon_back = findViewById(R.id.icon_back);
        tv_manorgirltezhi = findViewById(R.id.tv_manorgirltezhi);
        getRequest();
        String sexpait = MmkvUtil.INSTANCE.decodeString("sexpait");
        if (sexpait.equals("1")) {
            //表示是男
            tv_manorgirltezhi.setText(R.string.mi_nixihuandenvshengtezhishi);
        } else {
            //表示是女
            tv_manorgirltezhi.setText(R.string.mi_nixihuandenanshengtezhishi);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getlabelList(tokens, EXTRA, "0");
    }

    private void getlabelList(String tokens, String extra, String gender) {
        NetUtils2.getInstance().getApiService().getlabelList(tokens, extra, MmkvUtil.INSTANCE.decodeString("sexpait"))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LogUtils.i("decryptStr", decryptStr);
                        Gson gson = new Gson();
                        LableBean bean = gson.fromJson(decryptStr, LableBean.class);
                        GridLayoutManager gridLayoutManager = new GridLayoutManager(Tezhi4Activity.this, 3, GridLayoutManager.VERTICAL, false);
                        rc_tezhi4.setLayoutManager(gridLayoutManager);
                        if (bean != null) {
                            if (bean.getData() != null) {
                                if (bean.getData().getLabels() != null && bean.getData().getLabels().size() != 0) {
                                    adapter = new Tezhi4RecyAdapter(bean.getData().getLabels());
                                    rc_tezhi4.setAdapter(adapter);
                                    adapter.setOnAddClickListener(new Tezhi4RecyAdapter.OnAddClickListener() {
                                        @Override
                                        public void onItemClicks(int position, int id, boolean isselect) {
                                            bean.getData().getLabels().get(position).setSelect(isselect);
                                            adapter.notifyDataSetChanged();
                                            if (isselect) {
                                                //选中的标签ID
                                                selectIds.add(id + "");
                                                LogUtils.i("已选中ID", selectIds);
                                            } else {
                                                //取消选中
                                                if (selectIds != null && selectIds.size() > 0) {
                                                    for (int i = 0; i < selectIds.size(); i++) {
                                                        if (selectIds.get(i).equals(id + "")) {
                                                            selectIds.remove(i);
                                                        }
                                                    }
                                                }
                                                LogUtils.i("已选中ID", selectIds.toString());
                                            }

                                            if (selectIds.size() >= 4) {
                                                btn_goup.setText(R.string.mi_xuanhaol);
                                                btn_goup.setTextColor(Color.WHITE);
                                                btn_goup.setBackgroundResource(R.drawable.bt_goup);
                                            } else {
                                                btn_goup.setText(R.string.mi_zhishaoxuanzejigebiaoqian);
                                                btn_goup.setTextColor(btn_goup.getResources().getColor(R.color.black999));
                                                btn_goup.setBackgroundResource(R.drawable.shape_bt_goup);
                                            }
                                        }
                                    });
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

}
